#!/bin/bash

# ksrcinit - Kernel module source initialization tool
# Usage: ksrcinit <module_name>

if [ $# -ne 1 ]; then
    echo "Error: One argument required - module name"
    echo "Usage: $0 <module_name>"
    exit 1
fi

MODULE_NAME=$1
SRC_FILE="${MODULE_NAME}.c"
MAKEFILE="Makefile"

if [[ ! "$MODULE_NAME" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
    echo "Error: Invalid module name '$MODULE_NAME'"
    echo "Module name must follow C identifier rules:"
    echo "  - Start with a letter (a-z, A-Z) or underscore (_)"
    echo "  - Contain only letters, numbers, and underscores"
    echo "  - Cannot start with a number"
    echo "  - Cannot contain hyphens, spaces, or special characters"
    exit 1
fi

if [ -f "$SRC_FILE" ]; then
    echo "Error: ${SRC_FILE} already exist! Choose different module name or remove existing files"
    exit 1
fi

if [ -f "$MAKEFILE" ]; then
    echo "Error: ${MAKEFILE} already exist!"
    exit 1
fi

cat > "$SRC_FILE" << EOF
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

static int __init ${MODULE_NAME}_init(void) {
    pr_info("${MODULE_NAME}: module_init\\n");
    return 0;
}

static void __exit ${MODULE_NAME}_exit(void) {
    pr_info("${MODULE_NAME}: module_exit\\n");
}

module_init(${MODULE_NAME}_init);
module_exit(${MODULE_NAME}_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("kdev");
MODULE_DESCRIPTION("A simple Linux driver");
MODULE_VERSION("0.1");
EOF

cat > "$MAKEFILE" << EOF
obj-m := ${MODULE_NAME}.o

KERNELDIR ?= /lib/modules/\$(shell uname -r)/build
PWD := \$(shell pwd)

all:
	\$(MAKE) -C \$(KERNELDIR) M=\$(PWD) modules

clean:
	\$(MAKE) -C \$(KERNELDIR) M=\$(PWD) clean

insmod: all
	insmod ${MODULE_NAME}.ko

rmmod:
	rmmod ${MODULE_NAME}

install:
	\$(MAKE) -C \$(KERNELDIR) M=\$(PWD) modules_install

test: clean all
	rmmod ${MODULE_NAME} || :
	dmesg -c &> /dev/null
	insmod ${MODULE_NAME}.ko
	dmesg

EOF

chmod 644 "$SRC_FILE"
chmod 644 "$MAKEFILE"

echo "Successfully created:"
echo "  - Source file: $SRC_FILE"
echo "  - Makefile: $MAKEFILE"
echo ""
echo "Build command: make"
echo "Clean command: make clean"
echo "Install command: sudo make install"
echo "Test command: sudo make test"
echo ""
echo "All ok!All done!"
